﻿using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using DeliveryManage.Models;
using System;
using Newtonsoft.Json;
using System.Threading;
using FluentScheduler;
using Common.SerializationHelper;
using System.Globalization;
using Common;
using System.IO;

namespace DeliveryManage
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static string WebUrl;//站域名
        public static Model.Sys_User UserTable;
        public static Dictionary<int, Model.Sys_User> UserList;
        public static DeliveryManage.Model.Sys_Config SysConfig;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            OrderMassageHandler.Instance.Start();//最新订单消息队列

            WebUrl = ConfigurationManager.AppSettings["WebUrl"];
            UserList = new Dictionary<int, Model.Sys_User>();
            DeliveryManage.DAL.Sys_User DalUser = new DAL.Sys_User();
            UserTable = DalUser.GetModel(10000);
            if (UserTable != null) 
            {
                UserList.Add(UserTable.Id, UserTable);
                DalUser.CreatUserTree(UserTable, UserList);
            }
            SysConfig = (DeliveryManage.Model.Sys_Config)SerializationHelper.Load(typeof(DeliveryManage.Model.Sys_Config), Common.Utils.GetXmlMapPath(Common.DTKeys.SYS_XML_CONFING));
            Models.EmailHandler.Instance.Start();//邮件发送队列

            #region 每1时执行的定时器
            Registry registry_Hour = new Registry();
            registry_Hour.Schedule(() =>
            {
                if (DateTime.Now.Hour == 1)//每日凌晨1点自动同步资源统计数据
                {
                }
            }).ToRunNow().AndEvery(1).Hours();
            
            JobManager.Initialize(registry_Hour);
            #endregion
        }

        /// <summary>
        /// 重写Application_PostAuthorizeRequest
        /// </summary>
        protected void Application_PostAuthorizeRequest()
        {
            //对Session的支持，不然运行调用会直接异常
            HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
        }

        protected void Application_Error(Object sender, EventArgs e)
        {
            Exception lastError = Server.GetLastError();
            if (lastError != null)
            {
                //异常信息
                string strExceptionMessage = string.Empty;

                //对HTTP 404做额外处理，其他错误全部当成500服务器错误
                HttpException httpError = lastError as HttpException;
                if (httpError != null)
                {
                    //获取错误代码
                    int httpCode = httpError.GetHttpCode();
                    strExceptionMessage = httpError.Message;
                    if (httpCode == 400 || httpCode == 404)
                    {
                        Response.StatusCode = 404;
                        //跳转到指定的静态404信息页面，根据需求自己更改URL
                        Response.Redirect("/Open/NotFound");
                        Server.ClearError();
                        Response.Close();
                        return;
                    }
                }
                string LogPath = Server.MapPath("/App_Data/Logs/");
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                LogPath = LogPath + DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss") + ".txt";
                try
                {
                    File.AppendAllText(LogPath, lastError.StackTrace + "\r\n" + lastError.Message);
                }
                catch 
                {
                }
                strExceptionMessage = string.Format("SYS-ERR File:{0}", LogPath);
                /*-----------------------------------------------------
                 * 此处代码可根据需求进行日志记录，或者处理其他业务流程
                 * ---------------------------------------------------*/
                Model.Sys_User u = Session["session_admin_info"] as Model.Sys_User;
                if (u != null)
                {
                    Logs(0, u.Id, strExceptionMessage);
                }
                else
                {
                    Logs(0, -1, strExceptionMessage);
                }
                /*
                 * 跳转到指定的http 500错误信息页面
                 * 跳转到静态页面一定要用Response.WriteFile方法                 
                 */
                //Response.StatusCode = 500;
                //Response.Redirect("/Open/Err");
                //Response.Close();
                ////一定要调用Server.ClearError()否则会触发错误详情页（就是黄页）
                //Server.ClearError();
                //Server.Transfer("~/HttpError/500.aspx");
            }
        }
        public static void Logs(int type, int uid, string msg)
        {
            DAL.Sys_Logs DalLogs = new DAL.Sys_Logs();
            Model.Sys_Logs sml = new Model.Sys_Logs();
            sml.LogTime = DateTime.Now;
            sml.LogTxt = msg;
            sml.Type = type;
            sml.Uid = uid;
            DalLogs.Add(sml);
        }
        private static Queue<string> queueList = new Queue<string>();
        /// <summary>
        /// 添加本地txt日志文件
        /// </summary>
        /// <param name="logmsg"></param>
        public static void AddLogsToTxt(string logmsg)
        {
            //queueList.Enqueue(logmsg);
            //while (queueList.Count > 0)
            //{
            //    lock (queueList)
            //    {
            //        if (queueList.Dequeue() != null) {
            //            NewMethod(queueList.Dequeue());
            //        }
            //    }
            //}
            NewMethod(logmsg);
        }

        private static void NewMethod(string logmsg)
        {
            string sFilePath = AppDomain.CurrentDomain.BaseDirectory + "logs\\" + DateTime.Now.ToString("yyyyMMdd");
            string sFileName = "log_" + DateTime.Now.ToString("dd") + ".log";
            sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
            }
            using (StreamWriter sw = new StreamWriter(sFileName, true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "   ---   " + logmsg);
                sw.Close();
            }
        }

    }
}
